package Demo20220129; /**
 * @author: LiuBoTao
 * @date: 2022/1/29
 * @ApiNote
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "SSEDemoServlet", value = "/SSEDemoServlet")
public class SSEDemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //要点1：将返回的消息头的content_type设置为：text/event-stream；
        response.setContentType("text/event-stream");
        response.setHeader("expires", "-1");
        response.setHeader("cache-control", "no-cache");
        //要点2：要发送的消息字符串的拼接格式一定要正确
        String str=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        //返回的格式要以“data:”开头，前端收到后也是取event.data来得到信息；
        //返回需要加上两个换行。否则收不到MessageEvent的返回
        String s = "data:"+str+"\n\n";
        response.getOutputStream().write(s.getBytes());
        //测试用
        System.out.println("SseDemoServlet2222");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
